<?php

namespace app\common\model;


use app\common\exception\ApiException;

class Comment extends BaseModel {
    public function getCreateTimeAttr($value) {
        return date('m月d H:i', $value);
    }

    public function subComment() {
        return $this->hasMany('Reply', 'belong_id', 'id')->field('id,user_id,send_id,create_time,content');
    }

    public function userInfo() {
        return $this->hasOne('User', 'id', 'user_id')->field('id,nickName,avatarUrl');
    }

    public function getCommentList($user_id) {
        $information             = model('Information')
            ->where(['user_id' => $user_id])
            ->select();
        $information             = collection($information)->toArray();
        $ids                     = array_column($information, 'id');
        $condition['message_id'] = ['in', $ids];
        $result = $this
            ->with(['userInfo'])
            ->where($condition)
            ->order(['create_time' => 'desc'])
            ->select();
        if (!$result) {
            throw new ApiException('没有相应的资讯留言', 200, config('code.fail'));
        }
        return $result;
    }

    public function getCommentListById($id, $type) {
        $condition['status']     = ['eq', config('code.status_show')];
        $condition['type']       = $type;
        $condition['message_id'] = $id;
        $order                   = ['create_time' => 'desc'];
        $result                  = $this
            ->with(['UserInfo',
                'subComment' => function ($query) {
                    return $query->with(['userInfo', 'sendInfo']);
                }
            ])
            ->where($condition)
            ->order($order)
            ->select();
        if (!$result) {
            throw new ApiException('获取评论列表失败', 200, config('code.fail'));
        }
        $total = $this->where($condition)->sum('replay_count');
        return [
            'total' => $total,
            'list'  => collection($result)->hidden(['update_time', 'status', 'user_id', 'type', 'sub_comment.belong_id', 'sub_comment.user_id', 'sub_comment.send_id', 'sub_comment.status', 'sub_comment.update_time'])
        ];
    }
}